package com.oasistudio.tk.connector.imp;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.oasistudio.tk.connector.TopAPIConnectorHelper;
import com.oasistudio.tk.connector.TopApiRequest;
import com.oasistudio.tk.connector.TopApiResponse;
import com.taobao.tbw.common.TBWContext;

public class TradesBoughtGetConnector implements TopAPIConnectorHelper {
	/*
	 * 交�??��?�??认�?询�???��???????��?�??�??认�?�??次�??��?�??�????? 
	 * 交�??��??????
	 * TRADE_NO_CREATE_PAY(没�???��???�?��?? 
	 * WAIT_BUYER_PAY(�??买�?�??) 
	 * WAIT_SELLER_SEND_GOODS(�???????��,??买�?已�?�? 
	 * WAIT_BUYER_CONFIRM_GOODS(�??买�?�???�货,?????已�?�? 
	 * TRADE_BUYER_SIGNED(买�?已�???货�?�??�??) 
	 * TRADE_FINISHED(交�????) 
	 * TRADE_CLOSED(交�??��?) 
	 * TRADE_CLOSED_BY_TAOBAO(交�?�??�???? 
	 * ALL_WAIT_PAY(???�?AIT_BUYER_PAY??RADE_NO_CREATE_PAY) 
	 * ALL_CLOSED(???�?RADE_CLOSED??RADE_CLOSED_BY_TAOBAO)
	 * */
	private String status;
	public TradesBoughtGetConnector() {
	}

	public void setStatus(String status){
		this.status = status;
	}
	@Override
	public Object asyncPaser(byte[] part) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getApiUrl() {
		TopApiRequest request = new TopApiRequest();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", TBWContext.getInstance().getAppKey());
		params.put("partner_id", "top-apitools");
		params.put("sign_method", "md5");
		params.put("format", "json");
		params.put("v", "2.0");

		params.put("method", "taobao.trades.bought.get");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		params.put("timestamp", sdf.format(calendar.getTime()));
		params.put("session", TBWContext.getInstance().getTopsession());
		//params.put("fields", "seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type");
		params.put("fields", "title,type,tid,total_fee,payment,post_fee,pic_path,num_iid,num,price,end_time,orders.title,orders.pic_path,orders.price,orders.oid,orders.num,orders.iid,orders.num_iid,orders.payment");
		params.put("end_created", sdf.format(calendar.getTime()));
		calendar.add(Calendar.MONTH, -3);
		params.put("start_created", sdf.format(calendar.getTime()));
		if(this.status !=null){
			params.put("status", status);
		}
		request.params = params;
		//System.out.println("mellon:TradesBoughtGetConnector.getApiUrl() TBWContext.getInstance().getAppKey() ="+TBWContext.getInstance().getAppKey());
		//System.out.println("mellon:TradesBoughtGetConnector.getApiUrl() TBWContext.getInstance().getTopsession() ="+TBWContext.getInstance().getTopsession());
		String url = request.generalRequestUrl(true);
		//System.out.println("mellon:TradesBoughtGetConnector.getApiUrl() url ="+url);
		return url;
	}

	/**
	 * �??�?????�???��? total_results Number ??��?��?交�?信�??��? trades Trade[] 交�?信�???��
	 * hash_next Boolean ??��???�?��
	 */
	@Override
	public Object syncPaser(byte[] all) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		BoughtInfo boughtInfo = new BoughtInfo();
		try {
			TopApiResponse response = new TopApiResponse("trades_bought_get_response");
			String str = new String(all, "UTF-8");
			//Log.d("return msg:", str);
			if (response.parseResult(str).success) {
				boughtInfo.isSuccess = true;
				JSONObject jsObj = response.data;
				boughtInfo.totalResults = jsObj.optInt("total_results");
				System.out.println("TradesBoughtGetConnection.syncPaser() boughtInfo.totalResults = "+boughtInfo.totalResults);
				System.out.println("TradesBoughtGetConnection.syncPaser() boughtInfo.hashNext = "+jsObj.optBoolean("has_next"));
				
				if (jsObj.has("has_next")) {
					boughtInfo.hashNext = jsObj.optBoolean("has_next");
				}
				if (jsObj.has("trades")) {
					JSONObject tradesJSON = jsObj.getJSONObject("trades");
					if (tradesJSON.has("trade")) {
						JSONArray tradesArray = tradesJSON.getJSONArray("trade");
						Trade[] trades = new Trade[tradesArray.length()];
						boughtInfo.trades = trades;
						for (int i = 0; i < tradesArray.length(); i++) {
							JSONObject trade = tradesArray.getJSONObject(i);
							trades[i] = new Trade();
							trades[i].tid = trade.optLong("tid");
							trades[i].post_fee = trade.optString("post_fee");
							trades[i].payment = trade.optString("payment");
							//System.out.println("mellon: TradesBoughtGetConnector.syncParser() tid = "+trade.optLong("tid"));
							//System.out.println("mellon: TradesBoughtGetConnector.syncParser() post_fee = "+trade.optString("post_fee"));
							//System.out.println("mellon: TradesBoughtGetConnector.syncParser() end_time = "+trade.optString("end_time"));
							if(trade.has("end_time")){//???交�?没�?end_time�??�???��?为�?�?								
								trades[i].end_time = sdf.parse(trade.optString("end_time"));
							}
							JSONArray ordersArray = trade.getJSONObject("orders").getJSONArray("order");
							Order[] orders = new Order[ordersArray.length()];
							trades[i].orders = orders;
							for(int o=0; o<ordersArray.length(); o++){
								JSONObject order = ordersArray.getJSONObject(o);
								orders[o] = new Order();
								orders[o].oid = order.optLong("oid");
								orders[o].itemId = order.optLong("num_iid");
								orders[o].num = order.optInt("num");
								orders[o].pic_path = order.optString("pic_path");
								orders[o].payment = order.optString("payment");
								orders[o].title = order.optString("title");
								orders[o].end_time = trades[i].end_time;
							}
						}
					}
				}
			} else {
				boughtInfo.isSuccess = false;
				boughtInfo.errCode = response.errCode;
				boughtInfo.errInfo = response.errInfo;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return boughtInfo;
	}

	public static class BoughtInfo {
		public String errCode;
		public String errInfo;
		public Boolean isSuccess;
		public Number totalResults;
		public Trade[] trades;
		public Boolean hashNext;
	}

	public static class Trade {
		public Number tid;// 交�?�??
		//public Number num;// �?��?��?
		//public String pic_path;// ????��??��?�?????交�????�??�?????�?���???????		
		public String post_fee;// �?��
		public String payment;// �?????
		//public String total_fee;// ??????
		//public String title;// ?????��/�????��
		//public Number itemId;// ????��?id
		public Order[] orders;//订�??��?�??�??交�?�?????�??�??�??�??�?���??
		public Date end_time;//交�?�???��?�?��认�??�交??????交�??��??��?�?				
		public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("tid:"+tid);
			//sb.append(";number:"+num);
			sb.append(";payment:"+payment);
			sb.append(";post_fee:"+post_fee);
			//sb.append(";total_fee:"+total_fee);
			//sb.append(";itemId:"+itemId);
			//sb.append(";title:"+title);
			//sb.append(";pic_path:"+pic_path);
			return sb.toString();
		}
	}
	
	public static class Order {
		public Number oid;//�???????		
		public Number itemId;//????��?ID
		public String payment;//�?????�??�??精确??�???��????:???�?200.07�?���?200?????计�????�??�?ayment = price * num + adjust_fee - discount_fee + post_fee(??���??�??订�??��?订�?�??????????���??�??订�??��??????��)�??�??款�????�??????��?主�????�????????�?????该�?段�??��?�?.00???建�?使�???????�?????????????��??????款�?�??�??
		//public String total_fee;//??????
		public Number num;//�?��?��?
		public String title;//?????��
		public String pic_path;//????��??��?
		public Date end_time;//交�?�???��?�?��认�??�交??????交�??��??��?�??��?订�?

		public String commission;//�??佣�?�??�?��??????�?���??�??;�??已�????客�?表信?????���??佣�?�?????�?top api?��?佣�?�???��?�?��?�佣???�????		
		public Short withdraw_status;//�??佣�????已�?�??�??�??�???��?�?????�??�?��?��?�?��空�???ommission为�????????��????�?
		public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("oid:"+oid);
			sb.append(";itemId:"+itemId);
			sb.append(";number:"+num);
			sb.append(";payment:"+payment);
			//sb.append(";total_fee:"+total_fee);
			sb.append(";title:"+title);
			sb.append(";pic_path:"+pic_path);
			return sb.toString();
		}
	}
}
